﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using ZFCNew.Code;

namespace ZFCNew.ViewModels
{
    public class MainPageModel : INotifyPropertyChanged
    {
        public ICommand LogoutCommand { get; private set; }
        public FacebookHelper Fb { get; private set; }
        public bool IsLoggedIn { get { return FacebookHelper.LoggedInUser != null; } }
       
        public MainPageModel()
        {
            try
            {
                Fb = new FacebookHelper();
                FacebookHelper.LoggedIn += FbLoggedIn;
                FacebookHelper.LoggedOut += FbLoggedOut;
                FacebookHelper.GetMainUserCompleted += Fb_GetMainUserCompleted;
            }
            catch (Exception)
            {
               // TODO: Problem with internet
            }
            
            LogoutCommand = new DelegateCommand(Logout, (s) => true);
            HtmlHelper.ShowLogin();
        }

        private void Logout(object s)
        {
            FacebookHelper.Logout();
        }

        private void Fb_GetMainUserCompleted(object sender, EventArgs e)
        {
            HtmlHelper.HideLogin();
            Deployment.Current.Dispatcher.BeginInvoke(() => NotifyPropertyChanged("IsLoggedIn", "Fb"));
            GetFriends();
        }

       

        private void FbLoggedOut(object sender, EventArgs e)
        {
            HtmlHelper.ShowLogin();
            Deployment.Current.Dispatcher.BeginInvoke(() => NotifyPropertyChanged("IsLoggedIn","Fb"));
        }

        private void FbLoggedIn(object sender, EventArgs e)
        {
            GetMyProfile();
        }

        private void GetMyProfile()
        {
            Fb.GetMyInfo(); 
        }

        private void GetFriends()
        {
            FacebookHelper.GetFriends();
        }

        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(params String[] info)
        {
            if (PropertyChanged != null)
            {
                foreach (var s in info)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(s));  
                }
                
            }
        }

        #endregion
    }
}